﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;
using System.Collections;
using System.Text;
using System.Data;
using System.Drawing;

public partial class Administration_Articles : System.Web.UI.Page
{
    Articles current;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                litTitle.Text = "Editeaza un articol";
                pnlEdit.Visible = true;
                pnlSearch.Visible = false;
                BindEditForm(Convert.ToInt32(Request.QueryString["ID"]));
            }
            else
            {
                litTitle.Text = "Editeaza un articol :: Cautare";
            }
        }

        ContentPlaceHolder RightContentHolder = (ContentPlaceHolder)Master.FindControl("RightContentHolder");
        RightContentHolder.Visible = false;
    }

    private void BindEditForm(int articleID)
    {
        current = Entities.GetArticleDetails(articleID);
        ViewState["CurrentArticle"] = current;
        txtTitle.Text = current.Title;
        htmlContent.Content = current.Content;
        txtDatePosted.Text = current.DatePosted.Value.ToShortDateString();
        txtWebDesc.Text = current.MetaDesc;
        txtKeys.Text = current.MetaKeys;
        chApproved.Checked = current.Approved;
        chFeatured.Checked = (current.IsFeatured.HasValue) ? current.IsFeatured.Value : false;

        if (!string.IsNullOrEmpty(current.ImagePath))
        {
            Bitmap img = new Bitmap(Utils.GetApplicationSetting(Constants.IMAGES_ARTICLES_PHYSICAL_PATH) + current.ImagePath);
            if (img.Width > img.Height) imgCateg.Width = new Unit(250);
            else imgCateg.Height = new Unit(250);
            imgCateg.ImageUrl = Utils.GetApplicationSetting(Constants.IMAGES_ARTICLES_URL_PREFIX) + current.ImagePath;
        }
        else
            imgCateg.ImageUrl = Utils.GetApplicationSetting(Constants.IMAGES_ARTICLES_URL_PREFIX) + Constants.NO_IMAGE_FILE_NAME;

        if (!string.IsNullOrEmpty(current.FeaturedImage))
        {
            Bitmap img = new Bitmap(Utils.GetApplicationSetting(Constants.IMAGES_ARTICLES_PHYSICAL_PATH) + current.FeaturedImage);
            if (img.Width > img.Height) imgFeatured.Width = new Unit(250);
            else imgFeatured.Height = new Unit(250);
            imgFeatured.ImageUrl = Utils.GetApplicationSetting(Constants.IMAGES_ARTICLES_URL_PREFIX) + current.FeaturedImage;
        }
        else
            imgFeatured.Visible = false;

        LoadNavigation(current.Category);

        // parent category dropdown binder
        DataTable dt = Entities.GetTreeCategories();
        ddlParentCateg.Items.Clear();
        int level = -1;
        RecursiveFillTree(dt, 0, level);
        ddlParentCateg.SelectedValue = current.Category.CategoryID.ToString();
    }

    private void RecursiveFillTree(DataTable dtParent, int parentID, int level)
    {
        level++; //on the each call level increment 1
        System.Text.StringBuilder appender = new System.Text.StringBuilder();

        for (int j = 0; j < level; j++)
        {
            appender.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|");
        }
        if (level > 0)
        {
            appender.Append("_ ");
        }

        DataView dv = new DataView(dtParent);

        dv.RowFilter = string.Format("pid = {0}", parentID);
        dv.Sort = "title asc";
        int i;

        if (dv.Count > 0)
        {
            for (i = 0; i < dv.Count; i++)
            {
                ddlParentCateg.Items.Add(new ListItem(Server.HtmlDecode(appender.ToString() + dv[i]["Title"].ToString()), dv[i]["id"].ToString()));
                RecursiveFillTree(dtParent, int.Parse(dv[i]["id"].ToString()), level);
            }
        }
        level--; //on the each function end level will decrement by 1
    }
    protected string LoadNavigation(Categories categ)
    {
        StringBuilder sb = new StringBuilder();

        Categories current = categ;
        ArrayList nav = new ArrayList();
        nav.Add(current);
        while (current.Parent.CategoryID != 0)
        {
            try
            {
                current = current.Parent;
                nav.Add(current);
            }
            catch { break; }
        }
        for (int i = nav.Count - 1; i >= 0; i--)
        {
            Categories x = (Categories)nav[i];
            if (categ.CategoryID != Convert.ToInt32(x.CategoryID))
                sb.Append(@" » <a href=""categories.aspx?ID=" + x.CategoryID + @""">" + x.Title + @"</a>");
            else
                sb.Append(@" » " + x.Title);
        }
        return sb.ToString();
    }

    [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static object[] GetCompletionList(string prefixText, int count, string contextKey)
    {
        Articles[] articles = Entities.SearchArticles(prefixText);
        ArrayList s = new ArrayList();
        foreach (Articles art in articles)
        {
            s.Add(art.Title);
        }
        return s.ToArray();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        Articles[] articles = Entities.SearchArticles(txtSearch.Text);
        ViewState["FoundArticles"] = articles;
        repSearchResult.DataSource = articles;
        DataBind();
    }
    protected void repSearchResult_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Header)
        {
            Literal resultsCount = (Literal)e.Item.FindControl("litResultsCount");
            resultsCount.Text = ((Articles[])ViewState["FoundArticles"]).Length.ToString();
        }
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        current = (Articles)ViewState["CurrentArticle"];
        string imageFileName = uplImage.FileName;
        if (!string.IsNullOrEmpty(imageFileName))
        {
            uplImage.SaveAs(Utils.GetApplicationSetting(Constants.IMAGES_ARTICLES_PHYSICAL_PATH) + uplImage.FileName);
        }
        string featuredImageFileName = uplFeatured.FileName;
        if (!string.IsNullOrEmpty(featuredImageFileName))
        {
            uplFeatured.SaveAs(Utils.GetApplicationSetting(Constants.IMAGES_ARTICLES_PHYSICAL_PATH) + uplFeatured.FileName);
        }
        DateTime datePosted = (calDatePosted.SelectedDate.HasValue) ? calDatePosted.SelectedDate.Value : DateTime.Now;

        current = Entities.InsertOrUpdateArticle(
                current.ID,
                txtTitle.Text,
                htmlContent.Content,
                Convert.ToInt32(ddlParentCateg.SelectedValue),
                datePosted,
                txtWebDesc.Text,
                txtKeys.Text,
                imageFileName,
                chApproved.Checked,
                chFeatured.Checked,
                featuredImageFileName);
    }
}
